package org.skywork.top.core.flow.config;

import com.skywork.top.core.auto.props.SkyPropertySource;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.flowable.engine.impl.db.DbIdGenerator;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.skywork.top.core.flow.property.FlowProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(FlowProperty.class)
@SkyPropertySource(value = "classpath:/sky-flow.yml")
@ConditionalOnProperty(prefix = "sky.flow", name = "enabled", havingValue = "true")
public class FlowConfig  implements EngineConfigurationConfigurer<SpringProcessEngineConfiguration> {


    @Override
    public void configure(SpringProcessEngineConfiguration engineConfiguration) {
        engineConfiguration.setActivityFontName("宋体");
        engineConfiguration.setLabelFontName("宋体");
        engineConfiguration.setAnnotationFontName("宋体");
        engineConfiguration.setIdGenerator(new DbIdGenerator());
    }

    @Bean
    @ConditionalOnBean(DataSource.class)
    @ConditionalOnProperty(prefix = "sky.flow", name = "vender", havingValue = "flowable")
    public ProcessEngineConfiguration processEngineConfiguration(FlowProperty flowProperty) {
        ProcessEngineConfiguration config = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration();
        // 配置其他参数
        config.setDatabaseSchemaUpdate(flowProperty.getFlowable().getDatabaseSchemaUpdate());
        config.setAsyncExecutorActivate(flowProperty.getFlowable().getAsyncExecutorActivate());
        config.setHistoryLevel(flowProperty.getFlowable().getHistoryLevel());
        return config;
    }

    @Bean
    @ConditionalOnBean(ProcessEngineConfiguration.class)
    public ProcessEngine processEngine(ProcessEngineConfiguration config) {
        return config.buildProcessEngine();
    }

    @Bean
    @ConditionalOnBean(ProcessEngine.class)
    public RepositoryService repositoryService(ProcessEngine engine) {
        return engine.getRepositoryService();
    }


}
